package com.xuedongzhilian.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xuedongzhilian.dto.StudyPlanDTO;
import com.xuedongzhilian.entity.StudyPlan;
import com.xuedongzhilian.mapper.StudyPlanMapper;
import com.xuedongzhilian.service.IStudyPlanService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 学习计划服务实现类
 * </p>
 *
 * @author 学动智联团队
 * @since 2025-10-14
 */
@Service
public class StudyPlanServiceImpl implements IStudyPlanService {

    @Resource
    private StudyPlanMapper studyPlanMapper;

    @Override
    public boolean createStudyPlan(StudyPlanDTO studyPlanDTO) {
        StudyPlan studyPlan = BeanUtil.copyProperties(studyPlanDTO, StudyPlan.class);
        return studyPlanMapper.insert(studyPlan) > 0;
    }

    @Override
    public List<StudyPlanDTO> getStudyPlansByUserId(Long userId) {
        QueryWrapper<StudyPlan> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<StudyPlan> studyPlans = studyPlanMapper.selectList(queryWrapper);
        return studyPlans.stream()
                .map(studyPlan -> BeanUtil.copyProperties(studyPlan, StudyPlanDTO.class))
                .collect(Collectors.toList());
    }

    @Override
    public StudyPlanDTO getStudyPlanDetail(Long planId, Long userId) {
        QueryWrapper<StudyPlan> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", planId).eq("user_id", userId);
        StudyPlan studyPlan = studyPlanMapper.selectOne(queryWrapper);
        if (studyPlan == null) {
            return null;
        }
        return BeanUtil.copyProperties(studyPlan, StudyPlanDTO.class);
    }

    @Override
    public boolean updateStudyPlan(StudyPlanDTO studyPlanDTO) {
        StudyPlan studyPlan = BeanUtil.copyProperties(studyPlanDTO, StudyPlan.class);
        return studyPlanMapper.updateById(studyPlan) > 0;
    }

    @Override
    public boolean deleteStudyPlan(Long planId, Long userId) {
        QueryWrapper<StudyPlan> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", planId).eq("user_id", userId);
        return studyPlanMapper.delete(queryWrapper) > 0;
    }

    @Override
    public boolean completeStudyPlan(Long planId, Long userId) {
        StudyPlan studyPlan = new StudyPlan();
        studyPlan.setId(planId);
        studyPlan.setStatus(2); // 2表示已完成
        QueryWrapper<StudyPlan> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", planId).eq("user_id", userId);
        return studyPlanMapper.update(studyPlan, queryWrapper) > 0;
    }
}